package com.william.jdbcplus.core.interceptor;

import com.william.jdbcplus.core.query.EntityWrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.NamedThreadLocal;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
public class CrudInterceptor implements Interceptor {
    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime");

    @Override
    public boolean before(Object proxy, Object target, Method method, Object[] args) {
        // 1、开始时间
        long beginTime = System.currentTimeMillis();
        // 线程绑定变量（该数据只有当前请求的线程可见）
        startTimeThreadLocal.set(beginTime);
        log.info(String.format("%s : BEGIN--------------------", method.getName()));

        String methodName = method.getName();
        if (methodName.equals("insert")) {
            Object entity = args[0];
            insertInterceptor(Arrays.asList(entity));
        } else if (methodName.equals("insertList")) {
            List<Object> entityList = (List<Object>) args[0];
            insertInterceptor(entityList);
        } else if (methodName.equals("update")) {
            Map<String, Object> updateMap = (Map<String, Object>) args[0];
            EntityWrap<?> entityWrap = (EntityWrap<?>) args[1];
            updateInterceptor(updateMap, entityWrap);
        }
        //这里为false，则不调用目标原有方法，直接调用around的替代方法
        return true;
    }

    @Override
    public void after(Object proxy, Object target, Method method, Object[] args) {
        // 1、结束时间
        long endTime = System.currentTimeMillis();
        // 2、得到线程绑定的局部变量（开始时间）
        long beginTime = startTimeThreadLocal.get();
        // 3、消耗的时间
        long consumeTime = endTime - beginTime;
        log.info(String.format("%s : END {consume %d msec}--------------------", method.getName(), consumeTime));
    }


    @Override
    public void around(Object proxy, Object target, Method method, Object[] args) {

    }

    private void insertInterceptor(List<Object> entityList) {

    }

    private void updateInterceptor(Map<String, Object> updateMap, EntityWrap<?> entityWrap) {

    }
}